package github

import (
	"fmt"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gfer/app/model/user"
	"github.com/gogf/gfer/app/model/user_detail"
	url2 "net/url"
)

var clientId string
var clientSecret string
var redirectUri string
var authorizeUri string

func init() {
	gitConfig := g.Config().GetMapStrStr("github")
	clientId = gitConfig["ClientId"]
	clientSecret = gitConfig["ClientSecret"]
	redirectUri = url2.QueryEscape(gitConfig["RedirectUri"])
	authorizeUri = fmt.Sprintf(`https://github.com/login/oauth/authorize?client_id=%s&redirect_uri=%s`, clientId, redirectUri)
}

type C struct{}

func (c *C) Index(r *ghttp.Request) {
	r.Response.RedirectTo(authorizeUri)
}
func (c *C) Logout(r *ghttp.Request) {
	r.Session.Clear()
	r.Response.RedirectTo("http://localhost:8091")
}

func (c *C) Error500(r *ghttp.Request) {
	r.Response.WriteTpl("github.html")
}

func (c *C) Callback(r *ghttp.Request) {
	code := r.GetQueryString("code")
	params := g.Map{"client_id": clientId, "client_secret": clientSecret, "code": code}
	content := ghttp.PostContent("https://github.com/login/oauth/access_token", params)
	vals, _ := url2.ParseQuery(content)
	if vals.Get("error") != "" {
	}
	token := vals.Get("access_token")

	result := ghttp.GetContent("https://api.github.com/user?access_token=" + token)
	userJson, _ := gjson.LoadJson(result)
	userEntry := user.Entity{
		Nickname: userJson.GetString("login"),
	}
	entry, _ := user.FindOne(g.Map{"nickname": userEntry.Nickname})
	var userDetail *user_detail.Entity
	if entry == nil {
		userEntry.Token = token
		userEntry.Avatar = userJson.GetString("avatar_url")
		res, _ := userEntry.Save()
		userId, _ := res.LastInsertId()
		userDetail = &user_detail.Entity{
			Uid:    gconv.Uint(userId),
			Remark: result,
		}
		userDetail.Save()
	} else {
		entry.Avatar = userJson.GetString("avatar_url")
		entry.Token = token
		entry.Update()
		userDetail, _ = user_detail.FindOne(g.Map{"uid": entry.Id})
		userDetail.Remark = result
		userDetail.Update()
	}
	r.Session.Set("userInfo", result)
	r.Response.RedirectTo("http://localhost:8091")
}
